// 获取元素
let id = cookie.getItem('userId')
let contentBox = document.querySelector('.content')
let val = document.querySelector('.val')


init()

function init() {
  initValue()

  handleClick()
}

async function initValue() {
  let params = {
    url: '/cart/list',
    query: {
      id
    }
  }

  let res = await axios.get(params)
  console.log(res)
  if (res.code == 1) {
    let flag = res.cart.every(it => it.is_select)
    let num = 0
    let total = 0
    res.cart.forEach((it) => {
      if (it.is_select) {
        // num += it.cart_number
        num++
        total += it.current_price * it.cart_number
      }
    })
    let str = `<div class="top">
                        <input type="checkbox"  class="all" ${flag ? 'checked' : ''} > 全选
                    </div>
                    <ul>`
    // 循环创建li
    res.cart.forEach((item, index) => {
      str += `
             <li>
             <div class="status">
               <input type="checkbox" class='selectItem' data-goods_id='${item.goods_id}' ${item.is_select ? 'checked' : ''}>
             </div>
             <div class="show">
               <img src="${item.img_small_logo}" alt="">
             </div>
             <div class="title">
               ${item.title}
             </div>
             <div class="price">
               ￥ ${item.current_price}
             </div>
             <div class="number">
               <button data-goods_id='${item.goods_id}' class="sub">-</button>
               <input type="text" value="${item.cart_number}" class="val">
               <button data-goods_id='${item.goods_id}' class="sum">+</button>
             </div>
             <div class="sub">
               ￥ ${(item.current_price * item.cart_number).toFixed(2)}
             </div>
             <div class="destory">
               <button class='deleteItem' data-goods_id='${item.goods_id}'>删除</button>
             </div>
           </li>
             `
    })

    str += `
         </ul>
         <div class="bottom">
           <div class="totalNum">
             总件数 : ${num}
           </div>
           <div class="btns">
             <button class="clear">清空购物车</button>
             <button>去结算</button>
             <button class="rem">删除所有已选中</button>
           </div>
           <div class="totalPrice">
             总价格 : ￥ <span>${total.toFixed(2)}</span>
           </div>
         </div>
          
          `
    contentBox.innerHTML = str

  }
}


// 事件委派 操作购物车  

function handleClick() {
  contentBox.onclick = async (e) => {
    var e = e || window.event
    var target = e.target || e.srcElement

    // 单选 
    if (target.className == 'selectItem') {
      let params = {
        url: "/cart/select",
        query: {
          id,
          goodsId: target.dataset.goods_id
        }
      }

      let res = await axios.post(params)
      if (res.code == 1) {
        // 改变了状态  需要更新购物车的渲染
        initValue()
      }
    }

    // 全选留给你们做 



    // 删除 一条数据 

    if (target.className == 'deleteItem') {

      let result = confirm('你真的要删除么？')
      if (result) {
        let params = {
          url: "/cart/remove",
          query: {
            id,
            goodsId: target.dataset.goods_id
          }
        }
        let res = await axios.get(params)
        if (res.code == 1) {
          console.log(res)
          initValue()
        }
      }
    }


    //清空购物车
    if (target.className == 'clear') {

      let result = confirm('你真的要清空购物车吗？')
      if (result) {
        let params = {
          url: "/cart/clear",
          query: {
            id
          }
        }
        let res = await axios.get(params)
        if (res.code == 1) {
          console.log(res)
          initValue()
        }
      }
    }

    //删除选中
    if (target.className == 'rem') {

      let result = confirm('你真的要删除所有选中吗？')
      if (result) {
        let params = {
          url: "/cart/remove/select",
          query: {
            id
          }
        }
        let res = await axios.get(params)
        if (res.code == 1) {
          console.log(res)
          initValue()
        }
      }
    }

    //全选
    if (target.className == 'all') {
      let a = target.checked ? 1 : 0;
      let params = {
        url: "/cart/select/all",
        query: {
          id,
          type: a
        }
      }
      let res = await axios.post(params);
      if (res.code == 1) {
        console.log(res);
        initValue();
      }
    }

    //加减购买数量
    if (target.className == 'sub') {
      let params = {
        url: '/cart/number',
        query: {
          id,
          goodsId: target.dataset.goods_id,
          number: target.parentNode.children[1].value - 1
        }
      }

      let res = await axios.post(params);
      if (res.code == 1) {
        console.log(res);
        initValue();
      }
    }

    if (target.className == 'sum') {
      let params = {
        url: '/cart/number',
        query: {
          id,
          goodsId: target.dataset.goods_id,
          number: target.parentNode.children[1].value + 1
        }
      }

      let res = await axios.post(params);
      if (res.code == 1) {
        console.log(res);
        initValue();
      }
    }


  }
}